<?
    if (!is_writable($rootdir.'uploads')) {
        $smarty->assign('uploads_perm_fail', true);
    }

    $ID = '';
    if (isset($_GET['ID']))
    {
        $ID = $_GET['ID'];
    }
    if(isset($_POST['ID']))
    {
        $ID = $_POST['ID'];
    }
	
	// PROCESS SUBMISSION
	if (isset($_POST['entrytype']))
	{
       $is_bibtex = false;
	   if (isset($_POST['bibteximport']) && $_POST['bibteximport'] != '')
	   {
           $is_bibtex = true;
		   $bt = $_POST['bibteximport'];
		   foreach($_POST as $k=>$v)
		   {
				if ($k != 'meta' && $k != 'field_abstract')
				{
					$_POST[$k] = '';
				}
		   }
		   if (substr($bt,0,1) == '%') {
				   // Standard Reference Format
				   $bt = explode("\n", $bt);
				   foreach ($bt as $k=>$v) { $bt[$k] = split(" ", trim($v),2); }

				   // Type
				   $o = 'article';
				   foreach ($bt as $v) { if ($v[0] == '%0') $o = strtolower($v[1]); }
                   if ($o == 'journal article') $o = 'article';
				   $_POST['entrytype'] = $o;

				   // Authors
				   $o = '';
				   foreach ($bt as $v) { if ($v[0] == '%A') $o .= $v[1].' and '; }
				   $o = substr($o, 0, -5);
				   $_POST['field_author'] = $o;

				   // Title
				   $o = '';
				   foreach ($bt as $v) { if ($v[0] == '%T') $o = $v[1]; }
				   $_POST['field_title'] = $o;

				   // Journal
				   $o = '';
				   foreach ($bt as $v) { if ($v[0] == '%J') $o = $v[1]; }
				   $_POST['field_journal'] = $o;

				   // Year
				   $o = '';
				   foreach ($bt as $v) { if ($v[0] == '%D') $o = $v[1]; }
				   $_POST['field_year'] = $o;

				   // Volume
				   $o = '';
				   foreach ($bt as $v) { if ($v[0] == '%V') $o = $v[1]; }
				   $_POST['field_volume'] = $o;

				   // Number
				   $o = '';
				   foreach ($bt as $v) { if ($v[0] == '%N') $o = $v[1]; }
				   $_POST['field_number'] = $o;

				   // Pages
				   $o = '';
				   foreach ($bt as $v) { if ($v[0] == '%P') $o = str_replace("-","--",$v[1]); }
				   $_POST['field_pages'] = $o;

				   // Abstract
				   $o = '';
				   foreach ($bt as $v) { if ($v[0] == '%X') $o = $v[1]; }
				   $_POST['field_abstract'] = $o;

				   // Entry Key (Generated Here)
				   $firstauth = explode(",", $_POST['field_author']);
				   $firstauth = strtolower($firstauth[0]);
				   $_POST['field_entrykey'] = $firstauth.$_POST['field_year']; 
		   } else {
				   // We have a bibtex import so override what was entered.
			   
				   // Extract the entry type.
				   preg_match("/^@([a-zA-Z]*)\{/", $bt, $m);
				   if (!isset($m[1])) $error[] = "Malformed bibtex entry (entry type).  Unable to import.";
				   else $_POST['entrytype'] = $m[1];

				   // Extract the entry key.
				   preg_match("/^@[a-zA-Z]*\{([a-zA-Z0-9]*),/", $bt, $m);
				   if (!isset($m[1])) $error[] = "Malformed bibtex entry (entry key).  Unable to import.";
				   else $_POST['field_entrykey'] = $m[1];
				   
				   // Extract the fields.
				   preg_match_all("/([a-zA-Z]*)\s*=\s*\{*([^{}\n]*)\}*/", $bt, $m);
				   if (!isset($m[1])) $error[] = "Malformed bibtex entry (fields).  Unable to import.";
				   else
				   {
						foreach($m[1] as $k=>$v)
						{
							$_POST['field_'.$v] = $m[2][$k];
						}
				   }
		   }
        }
	
		$item = array();
		$fields = $bibtex->getFields($_POST['entrytype']);
		$item['entrytype'] = $_POST['entrytype'];
		$fields['req'][] = 'entrykey';
		foreach($fields['req'] as $v)
		{
            if (!isset($_POST['field_'.$v])) $_POST['field_'.$v] = '';
			$item[$v] = stripslashes($_POST['field_'.$v]);
			if (trim($_POST['field_'.$v]) == '')
			{
				$error[] = ucwords($v).' is a required field.';
			}
		}
		
		foreach($fields['opt'] as $v)
		{
            if (!isset($_POST['field_'.$v])) $_POST['field_'.$v] = '';
			$item[$v] = stripslashes($_POST['field_'.$v]);
		}
		
        if (!isset($_POST['field_abstract'])) $_POST['field_abstract'] = '';
		$item['abstract'] = stripslashes($_POST['field_abstract']);
		
		if ($ID == '' && !isset($_POST['ignoreDuplicate']))
		{	
            // Check entry key stuff including checking for duplicate
            if ($bibtex->getKeyID($_POST['field_entrykey']) !== false)
            {
                $e = 'Entry key already exists!<br />';
                $entry = $bibtex->getEntry($bibtex->getKeyID($_POST['field_entrykey']), true);
                $e .= '<span style="font-size: smaller;">'.$entry['author'].' ('.$entry['year'].'). '.$entry['title'].'. <em>'.$entry['journal'].'</em></span>';
                $error[] = $e;
            }
            
            $entry = $bibtex->duplicateSearch($item);
            
            if ($entry !== false)
            {
                $entry_formatted = '<span style="font-size: smaller;">'.$entry['author'].' ('.$entry['year'].'). '.$entry['title'].'. <em>'.$entry['journal'].'</em></span>';
                $error[] = 'Possible duplicate entry found.<br />'.$entry_formatted.'<br />To add this entry, please click the Save button again.';
                $smarty->assign('duplicate', $entry_formatted);
            }
        }

        if ($ID != '' && isset($_POST['deleteUpload']))
        {
            @unlink($rootdir.'uploads/'.$ID.'.pdf');
            @unlink($rootdir.'uploads/'.$ID.'_tn_preview.png');
            @unlink($rootdir.'uploads/'.$ID.'_preview.png');
        }
			
		if (count($error) == 0)
		{
			if (isset($_POST['ID']))
			{
                $ID = $_POST['ID'];
                $item['previewPage'] = $_POST['previewPage'];
                if ($_POST['previewPage'] != $_POST['oldPreviewPage'])
                {
                    @unlink($rootdir.'uploads/'.$ID.'_preview.png');
                    @unlink($rootdir.'uploads/'.$ID.'_tn_preview.png');
                }
                $new = false;
			}
			else
			{
			    $ID = '';
			    $item['user'] = $user->getUsername();
			    $new = true;
			}
		      
			$r = $bibtex->saveEntry($ID, $item);	
		
			if ($r === true)
			{
			    // Handle exciting file upload stuff
                if ($ID == '')
                {
                    $ID = $db->lastInsertID();
                }
                $dest = $rootdir.'uploads/';                 
			    if (isset($_FILES['file']) && $_FILES['file']['name'] != '') // A new upload takes priority
			    {
                    $ext = substr($_FILES['file']['name'], strrpos($_FILES['file']['name'], '.') + 1);
                    move_uploaded_file($_FILES['file']['tmp_name'], $dest.$ID.'.'.$ext); 
			    }
			    elseif (isset($_SESSION['tmpfile']))
			    {
                    $ext = substr($_SESSION['tmpfile_name'], strrpos($_SESSION['tmpfile_name'], '.') + 1);
                    rename($_SESSION['tmpfile'], $dest.$ID.'.'.$ext);
			    }
			    
			    foreach($_POST['meta'] as $k=>$v)
			    {
			         $bibtex->saveMeta($user->getID(), $ID, $k, $v);
			    }
			
			    unset($_SESSION['tmpfile']);
			    unset($_SESSION['tmpfile_name']);
		     
				$note[] = ucwords($_POST['entrytype']).' saved sucessfully!';
				$_FILES = array();

                if ($new && $is_bibtex)
                {
				    refreshPage('edit', array('ID'=>$ID));
				    $_POST = array(); // Clear the $_POST variable so it's like a brand new beginning to life.
				    $ID = '';
				}
                elseif ($new && !$is_bibtex)
                {
				    refreshPage('view', array('ID'=>$ID));
				    $_POST = array(); // Clear the $_POST variable so it's like a brand new beginning to life.
				    $ID = '';
				}
				else
				{
				    refreshPage('view', array('ID'=>$ID));
				}
			}
			else
			{
				$error[] = $r;
			}
		}
		
	}	
	else
	{
        // We didn't just process a submission.  So we definitely don't have to hold onto any temporary files.
        unset($_SESSION['tmpfile']);
        unset($_SESSION['tmpfile_name']);
        
        if ($ID != '')
        {
            if ($bibtex->getFilename($ID) !== false)
            {
                $_SESSION['tmpfile_name'] = '<a href="uploads/'.$bibtex->getFilename($ID).'">Download Here</a>';
            }
        }
	}

    $entry = array();
    $smarty->assign('addnew', true);
    if ($ID != '')
    {
        $smarty->assign('addnew', false);
        $entry = $bibtex->getEntry($ID, true);
        $smarty->assign('fields', array($bibtex->getFields($entry['entrytype'])));
        $smarty->assign('entryID', $ID);

        $smarty->assign('previewPages', array(1=>1,2=>2,3=>3,4=>4,5=>5));
        $smarty->assign('previewPage', $entry['previewPage']);
    }
    else
    {
        $smarty->assign('fields', $bibtex->getFields());
    }

    $smarty->assign('types', $bibtex->getTypes());
    
    // Assign values for the form to use
	foreach($bibtex->getFields() as $field)
	{
	    $field['req'][] = 'entrykey';
		foreach(array_merge($field['req'], $field['opt']) as $i)
		{
			if (isset($_POST['field_'.$i]))
			{
				$values[$i] = $_POST['field_'.$i];
			}
			elseif(isset($entry[$i]))
			{
                $values[$i] = $entry[$i];
			}
			else
			{
				$values[$i] = '';
			}
		}
	}
	if (isset($_POST['field_abstract']))
	{
	   $values['abstract'] = $_POST['field_abstract'];
    }     
	elseif (isset($entry['abstract']))
	{
	   $values['abstract'] = $entry['abstract'];
    }   
    else
    {
        $values['abstract'] = '';
    }  

	if (isset($_FILES['file']) && $_FILES['file']['name'] != '')
	{	   
	   $tmpFileName = $tmpdir.'/'.md5($_FILES['file']['name']);
       move_uploaded_file($_FILES['file']['tmp_name'], $tmpFileName); 	   
	   $_SESSION['tmpfile'] = $tmpFileName;
	   $_SESSION['tmpfile_name'] = $_FILES['file']['name'];
	}

	$smarty->assign('values', $values);
	$entrytype = 'article';
	if (isset($_POST['entrytype']))
	{
		$entrytype = $_POST['entrytype'];
	}
	$smarty->assign('entrytype', $entrytype);	


    function downloadPDF($url) {
       global $tmpdir;
       $tmpFileName = $tmpdir.'/'.md5($url.rand(0,1000));
       $_SESSION['tmpfile'] = $tmpFileName;
       $_SESSION['tmpfile_name'] = 'imported.pdf';
       $wget = 'wget -O "'.$tmpFileName.'" "'.$url.'"';
       shell_exec($wget);       
    }

    function downloadCitation($url) {
        $snoopy = new Snoopy();
        $snoopy->agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)";
        $snoopy->curl_path = "/usr/bin/curl";
        if ($snoopy->fetchtext($url)) {
            $r = htmlspecialchars($snoopy->results);
            return $r;
        } else {
            return "Error downloading citation.";
        }
    }

	if (isset($_GET['import'])) {
        switch ($_GET['import']) {

            case 'scholarsportal':
                $url = 'http://scholarsportal.info/cgi-bin/sciserv.pl?form=refer&collection='.$_GET['collection'].'&journal='.$_GET['journal'].'&issue='.$_GET['issue'].'&article='.$_GET['article'];
                $smarty->assign('bibImport', downloadCitation($url));
                $url = 'http://scholarsportal.info/cgi-bin/sciserv.pl?collection='.$_GET['collection'].'&journal='.$_GET['journal'].'&issue='.$_GET['issue'].'&article='.$_GET['article'].'&form=pdf&file=file.pdf';	
                downloadPDF($url);
               break;
            
            case 'jneurosci':
                $url = 'http://www.jneurosci.org/cgi/citmgr?type=bibtex&gca=jneuro;'.$_GET['code'];
                $smarty->assign('bibImport', downloadCitation($url));
                $url = 'http://www.jneurosci.org/cgi/reprint/'.$_GET['code'].'.pdf';
                downloadPDF($url);
                break;

            case 'jneurophys':
                $url = 'http://jn.physiology.org/cgi/citmgr?type=bibtex&gca=jn;'.$_GET['code'];
                $smarty->assign('bibImport', downloadCitation($url));
                $url = 'http:/jn.physiology.org/cgi/reprint/'.$_GET['code'].'.pdf';
                downloadPDF($url);
                break;

            case 'spnro':
                $url = 'http://online.sagepub.com/cgi/citmgr?type=endnote&gca=spnro;'.$_GET['code'];
                $smarty->assign('bibImport', downloadCitation($url));
                $url = 'http://spnro.sagepub.com/cgi/reprint/'.$_GET['code'].'.pdf';
                downloadPDF($url);
                break;
        }
	}
	
	if (isset($_SESSION['tmpfile_name']))
	{	
	   $smarty->assign('tmpfile', $_SESSION['tmpfile_name']);	   
	}
		
	
	/*****************************************************
	 Metadata Excitement Happens Hear and You're Invited
     *****************************************************/
    $smarty->assign('metafields', $bibtex->getMetaFields($user->getID()));
    $smarty->assign('metavalues', $bibtex->getMetaValues($user->getID(), $ID));
       
    if (isset($_POST['meta']))
    {
        // A POST takes precedence or previously saved values if any.
        $values = array();
        foreach($_POST['meta'] as $k=>$v)
        {
            $values[$k] = $v;
        }
        $smarty->assign('metavalues', $values);
    }
	
?>
